package cn.edu.nit.sys.service.impl;

import cn.edu.nit.sys.entity.Menu;
import cn.edu.nit.sys.entity.Role;
import cn.edu.nit.sys.mapper.MenuMapper;
import cn.edu.nit.sys.mapper.RoleMapper;
import cn.edu.nit.sys.service.RoleService;
import cn.edu.nit.sys.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author xiaobai
 * @Date 2022/9/4 19:43
 * @Version 1.0.0
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public R getRoleList(String name) {
        List<Role> roleList = baseMapper.getRoleList(name);
        return R.ok(roleList);
    }


    @Override
    public R updateRole(Role role) {
        String menuStr = "";
        List<Menu> menuById = menuMapper.getMenuById(role.getMenuList());
        for(int i = 0; i < menuById.size(); i++) {
            if(i < menuById.size() - 1) {
                menuStr += menuById.get(i).getLabel() + ",";
            }else {
                menuStr += menuById.get(i).getLabel();
            }
        }
        role.setMenus(menuStr);
        int i = baseMapper.updateById(role);
        return i > 0 ? R.ok("修改成功") : R.error("修改失败");
    }

    @Override
    public R addRole(Role role) {
        String menuStr = "";
        // List<Menu> menuById = menuMapper.getMenuById(role.getMenuList());
        // for(int i = 0; i < menuById.size(); i++) {
        //     if(i < menuById.size() - 1) {
        //         menuStr += menuById.get(i).getLabel() + ",";
        //     }else {
        //         menuStr += menuById.get(i).getLabel();
        //     }
        // }
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("name", role.getName())
                .or()
                .eq("role", role.getRole());
        Role selectOne = baseMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(selectOne)) {
            return R.error("角色名称或标识已存在");
        }
        Integer addRole = baseMapper.addRole(role, menuStr);
        if(addRole > 0) {
            return R.ok("添加成功");
        }
        return R.error("添加失败");
    }
}
